<template>
  <div class="store-list">
    <search-header
      ref="search"
      :single="false"
      :middle="false"
      :limit="limit"
      type="store"
      @getResultByTag="getResultByTag"
      @resetResult="resetResult"
    />
    <el-row class="count">
      <el-col :span="6">
        <el-tag type="success">店铺数量：{{ total }}</el-tag>
        <!-- 店铺数量：1000 -->
      </el-col>
      <el-col :span="6">
        <el-tag type="success">销售总额：{{ sales }}</el-tag>
        <!-- 店铺数量：1000 -->
      </el-col>
      <el-col :span="6">
        <el-tag type="success">共享店铺数量：300</el-tag>
        <!-- 店铺数量：1000 -->
      </el-col>
    </el-row>
    <el-card>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed prop="storeNum" label="店铺编号" width="80" />
        <el-table-column label="店铺名称" width="120">
          <template slot-scope="{ row }">
            <span>{{ row.storeName + ' - ' + row.subStoreName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="店铺行业" width="100">
          <template slot-scope="{ row }">
            <span>{{ row.storeIndustryErinId | storeIndustryErins }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="storeAddress"
          label="店铺地址"
          width="150"
        />
        <el-table-column prop="storePhone" label="联系电话" width="120" />
        <el-table-column prop="promoterId" label="推广人ID" width="100" />
        <el-table-column prop="levelOfEquity" label="权益级别" width="100" />
        <el-table-column prop="durationOfEquity" label="权益时限" width="100">
          <template slot-scope="{ row }">
            <span>{{ row.durationOfEquity + ' 天' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="销售额" width="100" sortable>
          <template slot-scope="{ row }">
            <span>{{ row.sales + ' 元' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="statusOfStore" label="运营状态" width="100" />
        <el-table-column prop="status" label="状态" width="100" />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="remark"
          label="备注"
          width="150"
        />
        <el-table-column fixed="right" label="操作" width="240">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              size="small"
              @click="viewClick(row.storeNum)"
            >查看</el-button>
            <el-button
              type="text"
              size="small"
              @click="viewGoods(row.id)"
            >查看商品</el-button>
            <el-button
              type="text"
              size="small"
              @click="analyzeClick(row.storeNum)"
            >经营分析</el-button>
            <el-button
              type="text"
              size="small"
              :disabled="row.status === '启用'"
              @click="openBtn(row)"
            >启用</el-button>
            <el-button
              type="text"
              size="small"
              class="delete"
              @click="delBtn(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          background
          :current-page.sync="currentPage"
          :page-sizes="[4, 6, 8, 10]"
          :page-size="limit"
          layout="sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getAllStore,
  getAllStoreList,
  getAllStoreListbyTag,
  delStoreById,
  openStoreById
} from '@/api/storeserin'
import { tidyTotal } from '@/filters'

export default {
  name: 'StoreList',
  components: {},
  props: {},
  data() {
    return {
      tableData: [], // 店铺列表
      currentPage: 1, // 当前也
      page: 1, // 默认是第一页
      limit: 4, // 请求的店铺数
      total: 0,
      sales: 0,
      searchList: []
    }
  },
  computed: {
    storeName() {
      return this.$refs.search.oldStoreName
    },
    storeCategory() {
      return this.$refs.search.oldStoreCategory
    }
  },
  watch: {},
  created() {
    // 获取总条数
    this.getAllStore()
    this.getAllStoreList()
  },
  mounted() {},
  methods: {
    // 获取总条数
    async getAllStore() {
      const res = await getAllStore()
      this.total = res ? res.length : 0
      // 计算销售总额
      this.getSales(res)
    },
    // 获取所有店铺列表
    async getAllStoreList() {
      const res = await getAllStoreList(this.page, this.limit)
      this.tableData = res || []
    },
    // 根据关键字获取所有店铺列表的总条数
    async getStoreNumsByTag() {
      let storeCategory = this.storeCategory
      if (this.storeCategory === '全部' || !this.storeCategory) {
        storeCategory = undefined
      }
      const res1 = await getAllStoreListbyTag({
        storeName_like: this.storeName,
        storeIndustryErinId: storeCategory
      })
      const res2 = await getAllStoreListbyTag({
        storeNum_like: this.storeName,
        storeIndustryErinId: storeCategory
      })
      const res3 = await getAllStoreListbyTag({
        subStoreName_like: this.storeName,
        storeIndustryErinId: storeCategory
      })
      const res = [res1, res2, res3]
      this.total = tidyTotal(res)
      this.getSales(res)
      this.tableData = tidyTotal(res).slice(0, this.limit)
    },
    viewClick(storeNum) {
      // 跳转页面
      this.$router.push(`/stores/details/${storeNum}`)
    },
    analyzeClick(storeNum) {
      this.$router.push(`/stores/salesAnalyze/${storeNum}`)
    },
    viewGoods(id) {
      // this.$router.push(`/stores/goods:${id}`)
      // 用name -->指组件的名字  的方法来跳转路径， 并且页面看不到传递的仓鼠 然后在调用页面获取id let id  = this.$route.params.id
      this.$router.push({ name: 'goodsList', params: { id: id }})
    },
    // pageSize 改变时会触发
    handleSizeChange(val) {
      this.limit = val
      if (this.isSearch()) {
        // 有内容
        // this.getAllStoreListbyTag()
        this.tableData = this.searchList.slice(
          val * (this.page - 1),
          val * this.page
        )
      } else {
        this.getAllStoreList()
      }
      // console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.page = val
      // console.log(`当前页: ${val}`)
      if (this.isSearch()) {
        // 有内容
        // this.getAllStoreListbyTag()
        this.tableData = this.searchList.slice(
          this.limit * (val - 1),
          this.limit * val
        )
      } else {
        this.getAllStoreList()
      }
    },
    // 子组件传过来根据内容查询到的数据
    getResultByTag(val, total) {
      // 页码要在第一页
      this.currentPage = 1
      // 需要total
      this.tableData = val
      this.total = total.length
      this.getSales(total)
      // 切页的时候用，因为根据查询的数据来切页，会有bug
      this.searchList = total
    },
    // 需要区分一下头部查询框中有没有内容
    isSearch() {
      return this.$refs.search.isClickSearch
    },
    // 重置数据
    resetResult() {
      this.getAllStoreList()
      this.getAllStore()
    },
    // 计算总额
    getSales(arr) {
      let sum = 0
      if (arr) {
        arr.forEach(item => {
          sum += parseFloat(item.sales)
        })
        this.sales = sum
      } else {
        this.sales = sum
      }
    },
    // 删除店铺信息
    async delBtn(id) {
      try {
        await this.$confirm('确定要删除店铺吗？此操作不可逆')
        await delStoreById(id)
        this.getDataAgain()
        this.$message.success('删除店铺成功')
      } catch (error) {
        // console.log(2)
      }
    },
    // 启用店铺信息
    async openBtn(row) {
      try {
        await openStoreById({
          ...row,
          status: '启用'
        })
        this.getDataAgain()
        this.$message.success('开启成功')
      } catch (error) {
        this.$message.error('开启失败')
      }
    },
    // 重新拉取
    // 依旧按照不同的情况拉取
    getDataAgain() {
      // 检查table中还有最后一条数据，这个时候，需要改变page的值了
      if (this.tableData.length === 1) {
        this.page--
      }
      if (this.isSearch()) {
        // 有内容
        this.getStoreNumsByTag() // 条数
      } else {
        // 没有内容
        this.getAllStore() // 条数
        this.getAllStoreList() // 列表
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '~@/styles/storeerin';
</style>
